/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package MyDate;

import java.util.*;
import javax.microedition.pim.*;
import sUtils.*;

/**
 *
 * @author Thomas.s
 */
public class PIMReader {

    Vector dates = new Vector(200,50);
    Vector special = new Vector(30,2);
    int ostern[] = new int[100];

    ContactList contacts = null;
    EventList events = null;
    ToDoList todos = null;
    PIM pim = PIM.getInstance();

    public PIMReader()
    {
        long t = System.currentTimeMillis()-TimeZone.getDefault().getRawOffset();
     
        calcOstern();
       
        open(false);

        Enumeration enums = null;
        if (contacts!=null)
        {
            try { enums = contacts.items(); } catch( Exception e ) { enums=null; }
            if (enums!=null) while (enums.hasMoreElements())
            {
                String name = null;
                long bday = 0;

                PIMItem contact = (PIMItem)(enums.nextElement());
                try { name = contact.getString(Contact.FORMATTED_NAME,0);} catch (Exception ep) { name = null; }
                try { bday = contact.getDate(Contact.BIRTHDAY,0); } catch (Exception ep) { name = null; }

                if (name!=null)
                {
                   dates.addElement( new MyDateEntry( name, bday, bday, 4, "", null ));
                }

            }
            enums = null;
        }

        if (events!=null)
        {
            try { enums = events.items(); } catch( Exception e ) { enums=null; }
            if (enums!=null) while (enums.hasMoreElements())
            {
                String name = null, uid = null;
                long time = 0, ende = 0;

                PIMItem ev = (PIMItem)(enums.nextElement());
                try { 
                    name = ev.getString(Event.SUMMARY,0);
                    if (name.charAt(0)=='~') name="";
                } catch (Exception ep) { name = null; }
                try {
                    String note = ev.getString(Event.NOTE,0);
                    if (note!=null && note.length()>0)
                    {
                        String noteshort = note.substring(0,name.length());
                        if (noteshort.equalsIgnoreCase(name)) note = note.substring(name.length());
                        if (name!=null && name.length()>0) {
                            if (name.length()==15) name = name + note; else
                                name = name + " " + note;
                        } else name = note;
                    }
                } catch (Exception ep) {}
                try { time = ev.getDate(Event.START,0);} catch (Exception ep) { time = 0; }
                try { ende = ev.getDate(Event.END,0);} catch (Exception ep) { ende = time+1; }
                try { uid = ev.getString(Event.UID,0);} catch (Exception ep) { uid = "--"; }
                //RepeatRule rep = ((Event)ev).getRepeat();
                //if (rep!=null) dates.addElement( new MyDateEntry( "repeat ", t, t, 1, "" ));

                if (name!=null && time!=0)
                {
                    String lower = name.toLowerCase();
                    int space = lower.indexOf(' ');
                    if (space>0) lower = lower.substring(0, space-1);
                    if (lower.equals("menstruation")||lower.equals("regel")||lower.equals("periode")||lower.equals("meno"))
                    {
                        special.addElement( new MyDateEntry( "Meno", time, ende, 3, uid, null ));
                    }
                    else
                    {
                        dates.addElement( new MyDateEntry( name, time, ende, 0, uid, null ));
                    }
                }

            }
            enums = null;
        }

        if (todos!=null)
        {
            try { enums = todos.items(); } catch( Exception e ) { enums=null; }
            if (enums!=null) while (enums.hasMoreElements())
            {
                String name = null, uid = null;
                long time = 0;

                PIMItem ev = (PIMItem)(enums.nextElement());
                try { name = ev.getString(ToDo.NOTE,0);} catch (Exception ep) { name = null; }
                if (name==null || name.equals("")) try { name = ev.getString(ToDo.SUMMARY,0);} catch (Exception ep) { name = null; }
                try { time = ev.getDate(ToDo.COMPLETION_DATE,0);} catch (Exception ep) { time = 0; }
                if (time==0) try { time = ev.getDate(Event.START,0);} catch (Exception ep) { time = 0; }
                try { uid = ev.getString(ToDo.UID,0);} catch (Exception ep) { uid = "--"; }

                if (name!=null)
                {
                    if (time==0) time = System.currentTimeMillis();
                    dates.addElement( new MyDateEntry( name, time, time, 5, uid, null ));
                }
            }
            enums = null;
            
        }
//        close();

    }

    void open( boolean readonly )
    {
        try { contacts = (ContactList)pim.openPIMList(PIM.CONTACT_LIST, readonly ? PIM.READ_ONLY : PIM.READ_WRITE); } catch( Exception e ){}
        try { events = (EventList)pim.openPIMList(PIM.EVENT_LIST, readonly ? PIM.READ_ONLY : PIM.READ_WRITE); } catch( Exception e ){}
        try { todos = (ToDoList)pim.openPIMList(PIM.TODO_LIST, readonly ? PIM.READ_ONLY : PIM.READ_WRITE); } catch( Exception e ){}
    }

    void openEvents( boolean readonly )
    {
        try { events = (EventList)pim.openPIMList(PIM.EVENT_LIST, readonly ? PIM.READ_ONLY : PIM.READ_WRITE); } catch( Exception e ){}
    }

    void close()
    {
        if (contacts!=null) try { contacts.close(); } catch( Exception e ){}
        if (events!=null) try { events.close(); } catch( Exception e ){}
        if (todos!=null) try { todos.close(); } catch( Exception e ){}
        contacts =null;
        events =null;
        todos=null;
    }

    public int getMeno( long time )
    {
        int ret = 0;
        time /= (24*60*60*1000);

        long lastmeno = -1;
        for ( int i = 0; i<special.size(); i++ )
        {
            MyDateEntry e = ((MyDateEntry)special.elementAt(i));
            if (e.type==3)
            {
                long etime = e.time/(24*60*60*1000);

                if (etime<=time && etime>=lastmeno) lastmeno = etime;
            }
        }
        if (lastmeno!=-1)
        {

            time -= lastmeno;
            time = ((time%28)+28)%28;

            if (time<4) ret = ( time<2 ? -2 : -1 ); else
            if (time>=9 && time<=15) ret = (time==9||time==15) ? 1 : 2;
        }
        return ret;
    }

    public void calcOstern()
    {
        int a,k,m,d,s,r,og,sz;
        for ( int x=2010; x<2110; x++ )
        {
            a = x%19;
            k = x/100;
            m = 15+((3*k+3)/4)-((8*k+13)/25);
            d = (19*a + m)%30;
            s = 2-(3*k+3)/4;
            r = d/29+(d/28-d/29)*(a/11);
            og = 21 + d-r;
            sz = 7 - (x+x/4+s)%7;
            ostern[x-2010] = 7 - (og-sz)%7 + og;
        }
    }

    public boolean editEvent( Event e, String name, long time, int hh, int mm, int len, int alarm )
    {
        boolean rc = true;
        final long etime = time;
        final String ename = name;
        final int ehh = hh;
        final int emm = mm;
        final int ealarm = alarm;
        final int elen = len;
        final Event ev = e;

        if (e!=null)
        {
          new Thread (
          new Runnable() {
          public void run () {
          try {

            String s="";
            Date d = new Date();
            d.setTime(etime);
            Calendar c = Calendar.getInstance();
            c.setTime(d);
            c.set(Calendar.HOUR_OF_DAY, ehh);
            c.set(Calendar.MINUTE, emm);
            d = c.getTime();
            long time = d.getTime();

            s = ename.length()>15 ? ename.substring(0,15) : ename;
            if (events.isSupportedField(Event.SUMMARY)) ev.addString(Event.SUMMARY, Event.ATTR_NONE, s );
            if (ename.length()>15 && events.isSupportedField(Event.NOTE)) ev.addString(Event.NOTE, Event.ATTR_NONE, ename );
            if (events.isSupportedField(Event.START)) ev.addDate(Event.START, Event.ATTR_NONE, time );
            if (events.isSupportedField(Event.END)) ev.addDate(Event.END, Event.ATTR_NONE, time+elen*60000 );
            if (ealarm>0 && events.isSupportedField(Event.ALARM)) ev.addInt(Event.ALARM, Event.ATTR_NONE, ealarm*60 );

            ev.commit();
            ev.notifyAll();
          } catch (Exception exc) { }
          }}).start ();
        }
        return rc;
    }


    public MyDateEntry createEntry( String name, long time, int hh, int mm, int len, int alarm )
    {
        MyDateEntry entry = null;
        //openEvents(false);
        if (events!=null)
        {
          Event e=null; 
          try { e = events.createEvent(); } catch (Exception exc) { e=null; }
          if (editEvent( e,name,time,hh,mm,len,alarm ))
          {
             String uid = "";
             dates.addElement( entry = new MyDateEntry( name, time,time+len*60000, 0, uid, e ));
          }
        }
        //close();
        return entry;
    }

    public boolean editEntry( String id, String name, long time, int hh, int mm, int len, int alarm )
    {
        boolean rc = false;
        Event e = null;
        if (events!=null)
        {
            Enumeration enums = null;
            String uid = null;
            try { enums = events.items(); } catch( Exception exp ) { enums=null; }
            if (enums!=null) while (enums.hasMoreElements() && !rc)
            {
                final Event ev = (Event)(enums.nextElement());
                try { uid = ev.getString(Event.UID,0); } catch (Exception ep) { uid = null; }
                if (uid!=null)
                    if (uid.equals(id))
                    {
                        editEvent( ev, name, time, hh, mm, len, alarm );
                        rc = true;
                        break;
                    }
            }
        }
        return rc;
    }

    public boolean removeEvent( String id )
    {
        if (id==null) return false;
        boolean rc = false;
        //open(false);
        if (events!=null)
        {
            Enumeration enums = null;
            String uid = null;
            try { enums = events.items(); } catch( Exception exp ) { enums=null; }
            if (enums!=null) while (enums.hasMoreElements() && !rc)
            {
                final Event ev = (Event)(enums.nextElement());
                try { uid = ev.getString(Event.UID,0); } catch (Exception ep) { uid = null; }
                if (uid!=null)
                try {
                    if (uid.equals(id)) {
                        new Thread (
                            new Runnable() {
                                public void run () {
                                    try { events.removeEvent (ev);
                                    } catch (Exception e) {}
                                }
                            }
                        ).start ();
                        rc = true;
                        break;
                    }
                } catch (Exception exp) { rc = false;  }
            }
        }
        //close();
        return rc;
    }

    public void addDates( MyDateDay day )
    {
        // Feste Feiertage:
        if (day.month==1)
        {
            if (day.day==1) day.addEntry( new MyDateEntry("Neujahr",day.timeStart,day.timeEnd,2,"",null)  ); else
            if (day.day==6) day.addEntry( new MyDateEntry("Heilige Drei Koenige",day.timeStart,day.timeEnd,2,"",null)  );
        } else
        if (day.month==10)
        {
            if (day.day==3) day.addEntry( new MyDateEntry("Tag der Einheit",day.timeStart,day.timeEnd,2,"",null)  ); else
            if (day.day==31) day.addEntry( new MyDateEntry("Reformationstag",day.timeStart,day.timeEnd,2,"",null)  );
        } else
        if (day.month==11)
        {
            if (day.day==1) day.addEntry( new MyDateEntry("Allerheiligen",day.timeStart,day.timeEnd,2,"",null)  );
        } else
        if (day.month==12) {
            if (day.day==25) day.addEntry( new MyDateEntry("1. Weihnachtstag",day.timeStart,day.timeEnd,2,"",null)  ); else
            if (day.day==26) day.addEntry( new MyDateEntry("2. Weihnachtstag",day.timeStart,day.timeEnd,2,"",null)  );
        } else
        {
            // Ostern:
            int dt = 0;
            if (day.month==3) dt = day.day; else
            if (day.month==4) dt = day.day+31; else
            if (day.month==5) dt = day.day+31+30; else
            if (day.month==6) dt = day.day+31+30+31;

            if (dt>0)
            {
                int os = ostern[day.year-2010];
                int mt = os+7*6-3;
                int pf = os+7*7;
                int fl = os+60;

                if (os-2==dt) day.addEntry( new MyDateEntry("Karfreitag",day.timeStart,day.timeEnd,2,"",null)  );
                if (os==dt)   day.addEntry( new MyDateEntry("Ostern",day.timeStart,day.timeEnd,2,"",null)  );
                if (os+1==dt) day.addEntry( new MyDateEntry("Ostermontag",day.timeStart,day.timeEnd,2,"",null)  );

                if (mt==dt)   day.addEntry( new MyDateEntry("Christi Himmelfahrt",day.timeStart,day.timeEnd,2,"",null)  );

                if (pf==dt)   day.addEntry( new MyDateEntry("Pfingstsonntag",day.timeStart,day.timeEnd,2,"",null)  );
                if (pf+1==dt) day.addEntry( new MyDateEntry("Pfingstmontag",day.timeStart,day.timeEnd,2,"",null)  );

                if (fl==dt)   day.addEntry( new MyDateEntry("Fronleichnam",day.timeStart,day.timeEnd,2,"",null)  );


            }

            if (day.month==5) { if (day.day==1) day.addEntry( new MyDateEntry("Maifeiertag",day.timeStart,day.timeEnd,2,"",null)  ); }

        }

        for ( int j=0; j<dates.size(); j++)
        {
            MyDateEntry e = (MyDateEntry)dates.elementAt(j);
            e.addTo(day);
        }


    }
}
